package com.kaiwukj.android.ufamily.mvp.ui.widget.home;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.content.res.AppCompatResources;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.gson.Gson;
import com.irozon.sneaker.widget.RoundedImageView;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.mvp.http.entity.bean.GuestBean;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.CommentResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.DoorAccessDeviceResult;
import com.kaiwukj.android.ufamily.mvp.ui.widget.RecycleJZVideoPlayer;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.zghl.mclient.client.ZghlMClient;
import com.zghl.mclient.client.ZghlStateListener;

import java.text.SimpleDateFormat;
import java.util.List;

import cn.jzvd.JZDataSource;
import cn.jzvd.JzvdStd;


public class PopupWindowUtil {

    @Deprecated
    private Context context;//??未使用

    private static OnEditDoneListener onEditDoneListener;
    private static OnPayClickListener onPayClickListener;

    public PopupWindowUtil(Context context) {
        this.context = context;
    }

    /**
     * 拨打电话弹窗
     */
    public static CustomPopupWindow createCallDialog(Activity activity, String text) {
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder(activity)
                .setAnimationStyle(R.anim.pop_enter_anim)
                .setFouse(true)
                .setOutSideCancel(false)
                .setwidth(ViewGroup.LayoutParams.MATCH_PARENT)
                .setheight(ViewGroup.LayoutParams.MATCH_PARENT)
                .setContentView(R.layout.dialog_confirm)
                .builder();
        TextView tvCancel = (TextView) customPopupWindow.getItemView(R.id.tv_cancel);
        TextView tvCall = (TextView) customPopupWindow.getItemView(R.id.tv_call);
        TextView tvPhone = (TextView) customPopupWindow.getItemView(R.id.tv_phone);
        tvCancel.setOnClickListener(view -> customPopupWindow.dismiss());
        tvPhone.setText(text);
        tvCall.setOnClickListener(view -> {
            Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + text));//跳转到拨号界面，同时传递电话号码
            activity.startActivity(dialIntent);
        });
        return customPopupWindow;
    }

    /**
     * 支付弹窗
     */
    public static CustomPopupWindow createPayDialog(Activity activity) {
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder(activity)
                .setAnimationStyle(R.anim.pop_enter_anim)
                .setFouse(true)
                .setOutSideCancel(true)
                .setwidth(ViewGroup.LayoutParams.MATCH_PARENT)
                .setheight(ViewGroup.LayoutParams.MATCH_PARENT)
                .setContentView(R.layout.dialog_pay)
                .builder();
        ImageView ivWechat = (ImageView) customPopupWindow.getItemView(R.id.iv_wechat_pay);
        ImageView ivAlipay = (ImageView) customPopupWindow.getItemView(R.id.iv_ali_pay);
        LinearLayout llEmpty = (LinearLayout) customPopupWindow.getItemView(R.id.ll_empty);
        ivWechat.setOnClickListener(view -> {
            onPayClickListener.OnPayClick(1);
            customPopupWindow.dismiss();
        });
        ivAlipay.setOnClickListener(view -> {
            onPayClickListener.OnPayClick(2);
            customPopupWindow.dismiss();
        });
        llEmpty.setOnClickListener(view -> {
            customPopupWindow.dismiss();
        });
        return customPopupWindow;
    }


    public interface OnPayClickListener {
        void OnPayClick(int type);
    }

    public void setOnPayClickListener(OnPayClickListener onPayClickListener) {
        this.onPayClickListener = onPayClickListener;
    }

    /**
     * 展示图片弹窗
     */
    public static CustomPopupWindow createImageDialog(Activity activity, String url) {
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder(activity)
                .setAnimationStyle(R.anim.pop_enter_anim)
                .setFouse(true)
                .setOutSideCancel(false)
                .setwidth(ViewGroup.LayoutParams.MATCH_PARENT)
                .setheight(ViewGroup.LayoutParams.MATCH_PARENT)
                .setContentView(R.layout.dialog_photo)
                .builder();
        ImageView imageView = (ImageView) customPopupWindow.getItemView(R.id.iv_image);
        Glide.with(activity).load(url).into(imageView);
        imageView.setOnClickListener(view -> customPopupWindow.dismiss());
        return customPopupWindow;
    }

    /**
     * 播放视频弹窗
     */
    /*@Deprecated
    public static CustomPopupWindow createVideoPlayerPop(Activity activity, String videoUrl, String coverUrl) {
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder(activity)
                .setAnimationStyle(R.anim.pop_enter_anim)
                .setFouse(true)
                .setOutSideCancel(false)
                .setwidth(ViewGroup.LayoutParams.MATCH_PARENT)
                .setheight(ViewGroup.LayoutParams.MATCH_PARENT)
                .setContentView(R.layout.pop_video_player)
                .builder();
        NiceVideoPlayer videoView = (NiceVideoPlayer) customPopupWindow.getItemView(R.id.video_player);
        RelativeLayout rlRoot = (RelativeLayout) customPopupWindow.getItemView(R.id.rl_root);
        rlRoot.setOnClickListener(view -> {
            videoView.release();
            customPopupWindow.dismiss();
        });
        videoView.setPlayerType(NiceVideoPlayer.TYPE_IJK);
        CommonVideoController controller = new CommonVideoController(activity);
        controller.imageView().setScaleType(ImageView.ScaleType.CENTER_CROP);
        Glide.with(activity).load(coverUrl).into(controller.imageView());
        videoView.setController(controller);
        videoView.setUp(videoUrl, null);
        customPopupWindow.getPopupWindow().setOnDismissListener(() -> {
            WindowUtil.setBackgroundAlpha(activity, 1f);
            if (videoView != null) {
                videoView.release();
            }
        });
        return customPopupWindow;
    }*/

    /**
     * 播放视频弹窗
     *
     * @param activity act
     * @param videoUrl 视频url
     * @param coverUrl 封面url
     * @return
     */
    public static CustomPopupWindow createVideoPop(Activity activity, String videoUrl, String coverUrl) {
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder(activity)
              //  .setAnimationStyle(R.anim.pop_enter_anim)
                .setFouse(true)
                .setOutSideCancel(false)
                .setwidth(ViewGroup.LayoutParams.MATCH_PARENT)
                .setheight(ViewGroup.LayoutParams.MATCH_PARENT)
                .setContentView(R.layout.pop_video_player_fix)
                .builder();
        RecycleJZVideoPlayer videoView = (RecycleJZVideoPlayer) customPopupWindow.getItemView(R.id.video_player);
        RelativeLayout rlRoot = (RelativeLayout) customPopupWindow.getItemView(R.id.rl_root);
        rlRoot.setOnClickListener(view -> {
            //videoView.release();
            customPopupWindow.dismiss();
        });

        customPopupWindow.getItemView(R.id.container_left).setOnClickListener(v -> customPopupWindow.dismiss());

        //videoView.setPlayerType(NiceVideoPlayer.TYPE_IJK);
        //CommonVideoController controller = new CommonVideoController(activity);
        //controller.imageView().setScaleType(ImageView.ScaleType.CENTER_CROP);
        JZDataSource jzDataSource = new JZDataSource(videoUrl);
        videoView.setUp(jzDataSource, JzvdStd.SCREEN_NORMAL);
        Glide.with(activity).load(coverUrl).into(videoView.posterImageView);
        videoView.startVideo();
        //videoView.setController(controller);
        //videoView.setUp(videoUrl, null);
        customPopupWindow.getPopupWindow().setOnDismissListener(() -> {
            WindowUtil.setBackgroundAlpha(activity, 1f);
            if (videoView != null) {
                JzvdStd.releaseAllVideos();
            }
        });
        return customPopupWindow;
    }

    /**
     * 评论列表弹窗
     */
    public CustomPopupWindow createCommentPop(Activity activity, List<CommentResult> data, int commentNum) {
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder(activity)
                .setAnimationStyle(R.style.PopupWindowAnimation)
                .setFouse(true)
                .setOutSideCancel(false)
                .setwidth(ViewGroup.LayoutParams.MATCH_PARENT)
                .setheight(ViewGroup.LayoutParams.MATCH_PARENT)
                .setContentView(R.layout.pop_video_comment)
                .builder();
        RecyclerView rvComment = (RecyclerView) customPopupWindow.getItemView(R.id.rv_comment);
        TextView tvNum = (TextView) customPopupWindow.getItemView(R.id.tv_num);
        ImageView ivCancel = (ImageView) customPopupWindow.getItemView(R.id.iv_cancel);
        EditText etEveluate = (EditText) customPopupWindow.getItemView(R.id.et_eveluate);
        TextView tvSend = (TextView) customPopupWindow.getItemView(R.id.tv_send);
        tvSend.setOnClickListener(view -> {
                    onEditDoneListener.OnEditDone(etEveluate.getText().toString());
                    etEveluate.setText("");
                }
        );
        tvNum.setText("评论" + commentNum);
        ivCancel.setOnClickListener(view -> customPopupWindow.dismiss());
        rvComment.setLayoutManager(new LinearLayoutManager(activity));
        rvComment.setAdapter(new BaseQuickAdapter<CommentResult, BaseViewHolder>(R.layout.item_video_comment, data) {

            @Override
            protected void convert(BaseViewHolder helper, CommentResult item) {
                RoundedImageView rivHead = helper.getView(R.id.riv_head);
                TextView tvName = helper.getView(R.id.tv_name);
                TextView tvContent = helper.getView(R.id.tv_content);
                TextView tvTime = helper.getView(R.id.tv_time);

                Glide.with(activity).load(item.getHeadImg()).into(rivHead);
                tvName.setText(item.getNickname());
                tvContent.setText(item.getCommentContent());
                tvTime.setText(item.getCreateTime());
            }
        });
        return customPopupWindow;
    }

    public interface OnEditDoneListener {
        void OnEditDone(String text);
    }

    public void setOnEditDoneListener(OnEditDoneListener onEditDoneListener) {
        this.onEditDoneListener = onEditDoneListener;
    }

    /**
     * 开门弹窗
     */

    private TextView selectedTextView;

    private RecyclerView rvGates;
    private LinearLayout llVerify;
    private TextView tvVerifyCode;
    private TextView tvCopy;
    private TextView tvDesc;
    private TextView tvTips;

    //    页面标识
    private int pageIndex;
    //    用户房屋关系ID
    private String zgORid;

    private QMUITipDialog dialog;

    public CustomPopupWindow createGateDialog(Activity activity, List<DoorAccessDeviceResult.UnitListBean> communityData, List<DoorAccessDeviceResult.UnitListBean> elementData, List<DoorAccessDeviceResult.UnitListBean> roomData) {
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder(activity)
                .setAnimationStyle(R.style.PopupWindowAnimation)
                .setFouse(true)
                .setOutSideCancel(false)
                .setwidth(ViewGroup.LayoutParams.MATCH_PARENT)
                .setheight(ViewGroup.LayoutParams.MATCH_PARENT)
                .setContentView(R.layout.dialog_gate)
                .builder();

        pageIndex = 1;

//        初始化控件
        TextView tvCommunityTab = (TextView) customPopupWindow.getItemView(R.id.tv_community_tab);
        TextView tvElementTab = (TextView) customPopupWindow.getItemView(R.id.tv_element_tab);
        TextView tvVerifyTab = (TextView) customPopupWindow.getItemView(R.id.tv_verify_tab);
        ImageView ivCancel = (ImageView) customPopupWindow.getItemView(R.id.iv_cancel);
        rvGates = (RecyclerView) customPopupWindow.getItemView(R.id.rv_gates);
        llVerify = (LinearLayout) customPopupWindow.getItemView(R.id.ll_verify);
        tvVerifyCode = (TextView) customPopupWindow.getItemView(R.id.tv_verify_code);
        tvCopy = (TextView) customPopupWindow.getItemView(R.id.tv_copy);
        tvDesc = (TextView) customPopupWindow.getItemView(R.id.tv_desc);
        tvTips = (TextView) customPopupWindow.getItemView(R.id.tv_tips);

//        tab点击事件
        tvCommunityTab.setOnClickListener(view -> {
            setSelected(tvCommunityTab);
            rvGates.setVisibility(View.VISIBLE);
            llVerify.setVisibility(View.GONE);
            setData(rvGates, communityData, activity);
            pageIndex = 1;
            tvTips.setVisibility(View.GONE);
        });
        tvElementTab.setOnClickListener(view -> {
            setSelected(tvElementTab);
            setData(rvGates, elementData, activity);
            rvGates.setVisibility(View.VISIBLE);
            llVerify.setVisibility(View.GONE);
            pageIndex = 2;
            tvTips.setVisibility(View.GONE);
        });
        tvVerifyTab.setOnClickListener(view -> {
            setSelected(tvVerifyTab);
            setData(rvGates, roomData, activity);
            rvGates.setVisibility(View.VISIBLE);
            llVerify.setVisibility(View.GONE);
            pageIndex = 3;
            tvTips.setVisibility(View.GONE);
        });
        ivCancel.setOnClickListener(view -> customPopupWindow.dismiss());

//        设置初始状态
        rvGates.setVisibility(View.VISIBLE);
        selectedTextView = tvCommunityTab;
        tvCommunityTab.setSelected(true);

//        社区门列表
        rvGates.setLayoutManager(new GridLayoutManager(activity, 3));
        setData(rvGates, communityData, activity);

        return customPopupWindow;
    }

    private void setData(RecyclerView recyclerView, List<DoorAccessDeviceResult.UnitListBean> data, Activity activity) {
        recyclerView.setAdapter(new BaseQuickAdapter<DoorAccessDeviceResult.UnitListBean, BaseViewHolder>(R.layout.item_community_gates, data) {
            @Override
            protected void convert(BaseViewHolder helper, DoorAccessDeviceResult.UnitListBean item) {
                RelativeLayout rlBg = helper.getView(R.id.rl_bg);
                TextView tvGateLock = helper.getView(R.id.tv_gate_lock);
                TextView tvGateName = helper.getView(R.id.tv_gate_name);
                tvGateName.setText(pageIndex == 3 ? item.getRoomName() : item.getName());
                switch (helper.getLayoutPosition() % 5) {
                    case 0:
                        rlBg.setBackground(AppCompatResources.getDrawable(activity, R.drawable.shape_gate_color1));
                        break;
                    case 1:
                        rlBg.setBackground(AppCompatResources.getDrawable(activity, R.drawable.shape_gate_color2));
                        break;
                    case 2:
                        rlBg.setBackground(AppCompatResources.getDrawable(activity, R.drawable.shape_gate_color3));
                        break;
                    case 3:
                        rlBg.setBackground(AppCompatResources.getDrawable(activity, R.drawable.shape_gate_color4));
                        break;
                    case 4:
                        rlBg.setBackground(AppCompatResources.getDrawable(activity, R.drawable.shape_gate_color5));
                        break;
                    case 5:
                        rlBg.setBackground(AppCompatResources.getDrawable(activity, R.drawable.shape_gate_color6));
                        break;
                }

                tvGateLock.setOnClickListener(view -> {
                    if (pageIndex == 3) {
                        zgORid = item.getZgORid();
                        rvGates.setVisibility(View.GONE);
                        llVerify.setVisibility(View.VISIBLE);

                        ZghlMClient.getInstance().getTempPassword(zgORid, new ZghlStateListener() {
                            @Override
                            public void onSuccess(int i, String s) {
                                if (!TextUtils.isEmpty(s)) {
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    GuestBean guestBean = new Gson().fromJson(s, GuestBean.class);
                                    tvVerifyCode.setText(guestBean.getPwd_value() + "");
                                    tvDesc.setText("可开启(" + item.getRoomName() + ")关联门禁该访客密码可在每台门禁机上使用2次，截止至" + simpleDateFormat.format(guestBean.getPwd_expired() * 1000) + "有效,在门禁机上点击”密码开门”，再输入密码直接开门");
                                } else {
                                    showMessage(activity, "获取失败，请重试");
                                }
                            }

                            @Override
                            public void onError(int i, String s) {
                                showMessage(activity, s);
                            }
                        });

                    } else {
                        showDialog(activity, "开启中...");
                        ZghlMClient.getInstance().openDoor(item.getDeviceId(), new ZghlStateListener() {
                            @Override
                            public void onSuccess(int i, String s) {
                                hideDialog();
                                tvGateLock.setSelected(true);
                                LogUtils.d("开门成功------------->" + s);
                            }

                            @Override
                            public void onError(int i, String s) {
                                hideDialog();
                                showMessage(activity, s);
                                LogUtils.e("开门失败-------------->" + s);
                            }
                        });
                    }
                });
                tvCopy.setOnClickListener(view -> {
                    if (!TextUtils.isEmpty(tvVerifyCode.getText().toString())) {
                        copy(tvVerifyCode.getText().toString(), activity);
                        tvTips.setVisibility(View.VISIBLE);
                    }
                });
            }
        });
    }

    private void setSelected(TextView textView) {
        if (textView != selectedTextView) {
            selectedTextView.setSelected(false);
            textView.setSelected(true);
            selectedTextView = textView;
        }
    }

    private boolean copy(String copyStr, Activity activity) {
        try {
            //获取剪贴板管理器
            ClipboardManager cm = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", copyStr);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private void showDialog(Activity activity, String message) {
        dialog = new QMUITipDialog.Builder(activity).setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING).setTipWord(message).create();
        dialog.setTitle(message);
        dialog.show();
    }

    private void hideDialog() {
        dialog.dismiss();
    }

    private void showMessage(Activity activity, String message) {
        QMUITipDialog messageDialog = new QMUITipDialog.Builder(activity).setTipWord(message).create();
        messageDialog.setTitle(message);
        messageDialog.show();
        new Handler().postDelayed(() -> messageDialog.dismiss(), 800);
    }

    private final static int COMMUNITY_TYPE = 1;
    private final static int ELEMENT_TYPE = 2;
    private final static int VERIFY_TYPE = 3;
}
